import {
  reportControllerCheckReport as checkReport,
  reportControllerCreateMonthReport as createReport,
} from '@/services/ess/diagnosisReport';
import { downloadFile } from '@/utils';
import { CheckCircleOutlined } from '@ant-design/icons';
import { message, Modal } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { useAccess, useIntl, useModel } from 'umi';
import Styles from './index.less';

const { confirm } = Modal;

export type Props = {
  date: string;
};

const Index: React.FC<Props> = ({ date }) => {
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const [reportId, setReportId] = useState('');
  const [disabled, setDisabled] = useState(false);
  const [initStatus, setInitStatus] = useState(false);
  const intl = useIntl();

  const updateReportStatus = async (date) => {
    try {
      const res = await checkReport({ date: moment(date)?.format('YYYY-MM-DD') });
      setInitStatus(true);
      if (res?.code === 10200 || res?.code === 10204) {
        setReportId('');
      }
      if (res?.success) {
        setReportId(res?.data?.id);
      }
    } catch (e) {
      setInitStatus(true);
      setReportId('');
    }
  };

  const download = (id) => {
    downloadFile(
      `/api/diagnosis/report/download?stationId=${stationId}&id=${id || reportId}&fileType=pdf`,
    );
  };

  useEffect(() => {
    if (date) {
      updateReportStatus(moment(date).format('YYYY-MM-DD'));
    }
  }, [date]);

  // 获取包含换行符的国际化字符串，并拆分成数组
  const generateReportsMessage = intl.formatMessage({ id: 'global.generateReports' }).split('\n');

  const downloadReportsMessage = intl.formatMessage({ id: 'global.downloadReports' }).split('\n');

  return (
    initStatus && (
      <div className={Styles.contentWrapper}>
        {reportId ? (
          <div
            className={Styles.exportReport}
            onClick={() => {
              download();
            }}
          >
            {moment(date).format('YYYY-MM') === moment().format('YYYY-MM') ? (
              <span>
                {downloadReportsMessage.map((line, index) => (
                  <React.Fragment key={index}>
                    {line}
                    {index !== downloadReportsMessage.length - 1 && <br />}
                  </React.Fragment>
                ))}
              </span>
            ) : (
              <span>
                立刻下载{moment(date).format('YYYY-MM')}
                <br />
                月度健康报告
              </span>
            )}
          </div>
        ) : moment(date).format('YYYY-MM') === moment().format('YYYY-MM') ? (
          <div
            className={Styles.generateReport}
            onClick={() => {
              if (disabled) {
                return;
              }
              setDisabled(true);
              confirm({
                title: intl.formatMessage({ id: 'global.prompt' }),
                content: intl.formatMessage({ id: 'global.doesGenerateReports' }),
                onOk: async () => {
                  try {
                    const res = await createReport({ date: moment(date)?.format('YYYY-MM-DD') });
                    if (res.success) {
                      //message.success('月度评估报告生成成功');
                      confirm({
                        title: intl.formatMessage({ id: 'global.prompt' }),
                        icon: (
                          <CheckCircleOutlined
                            style={{
                              color: '#1a6cfe',
                            }}
                          />
                        ),
                        content: intl.formatMessage({ id: 'global.doesDownloadReports' }),
                        okText: '下载',
                        cancelText: '取消',
                        onOk: async () => {
                          download(res.data.id);
                        },
                      });
                      updateReportStatus(date);
                      return true;
                    }
                    if (res.code === 10202) {
                      Modal.info({
                        title: intl.formatMessage({ id: 'global.prompt' }),
                        content: (
                          <div>{intl.formatMessage({ id: 'global.reportsGenerating' })}</div>
                        ),
                        onOk() {},
                      });
                    }
                  } catch (error) {
                    message.error(intl.formatMessage({ id: 'global.generationFailed' }));
                    return false;
                  }
                },
                afterClose: () => {
                  setDisabled(false);
                },
              });
            }}
          >
            {generateReportsMessage.map((line, index) => (
              <React.Fragment key={index}>
                {line}
                <br />
              </React.Fragment>
            ))}
          </div>
        ) : (
          <div className={Styles.disabledExportReport}>
            {moment(date).format('YYYY-MM') === moment().format('YYYY-MM') ? (
              <span>
                {downloadReportsMessage.map((line, index) => (
                  <React.Fragment key={index}>
                    {line}
                    {index !== downloadReportsMessage.length - 1 && <br />}
                  </React.Fragment>
                ))}
              </span>
            ) : (
              <span>
                立刻下载{moment(date).format('YYYY-MM')}
                <br />
                月度健康报告
              </span>
            )}
          </div>
        )}
      </div>
    )
  );
};

const HealthReport: React.FC<Props> = (props) => {
  const access = useAccess();
  if (!access.can('com:healthReport')) {
    return null;
  }
  return <Index {...props}></Index>;
};

export default HealthReport;
